//
//  CXTranslater.swift
//  CXExtens
//
//  Created by 陈警卫 on 2023-12-28.
//

import Foundation
import Alamofire
import XcodeKit
import SwiftyJSON

class CXTranslater {
    
    static func translater(_ invocation: XCSourceEditorCommandInvocation) {
        
        guard let range = invocation.buffer.selections.firstObject as? XCSourceTextRange else { return }
        var start = range.start.line
        var end = range.end.line
        
        if end > (invocation.buffer.lines.count - 1) {
            end = (invocation.buffer.lines.count - 1)
        }
        if start > end {
            start = end
        }
        var code = ""
        for lineNum in start...end {
            code += invocation.buffer.lines[lineNum] as! String
        }
        
        let dict = UserDefaults.standard.object(forKey: "translater")
        if let tr = (dict as? [String : String])?[code] {
            let line = end
            invocation.buffer.lines.insert(tr, at: line)
        }
        
        let q = code
        let appid = "20231227001922561"
        let salt = "\(Int(Date().timeIntervalSince1970))"
        let from = "en"
        let to = "zh"
        let secret = "IMfFp7CwkaRNolmLCtZw"
        let sign = (appid + q + salt + secret).md5()
        
        let param: [String : Any] = ["q": q, "appid": appid, "salt": salt, "from": from, "to": to, "sign": sign]
        let dataRequest = AF.request("https://fanyi-api.baidu.com/api/trans/vip/translate",
                                     method: .get,
                                     parameters: param)
        
        dataRequest.responseString { response in
            switch response.result {
            case .success:
                if let data = response.data {
                    let json = JSON(data)
                    let dst = "/**\(json["trans_result"][0]["dst"].stringValue)*/"
                    
                    if let bundleId = Bundle.main.bundleIdentifier {
                        UserDefaults.standard.removePersistentDomain(forName: bundleId)
                    }
                    
                    let dict: [String: String] = [code: dst]
                    UserDefaults.standard.setValue(dict, forKey: "translater")
                    UserDefaults.standard.synchronize()
                }
                break
            case .failure:
                break
            }
        }
    }
}


